package com.topcent.tioxyc.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.pojo.vo.ChenToChangesVO;
import com.topcent.tioxyc.pojo.vo.Lin;
import com.topcent.tioxyc.pojo.vo.ToChangeVO;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: weidian
 * @date: 2024/9/28 16:05
 * @Description: 这是一个付款单的接口类
 */
@Slf4j
@RestController
public class FuKuanDanController {


    @Autowired
    private RabbitTemplate rabbitTemplate;
    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";
    private static final String DATA_DELETE = "data_remove";

    private static final String SECRET = "KPIfb04KeXBOWkj3m9xDqKV9";

    @PostMapping("/callback")
    public String callback(@RequestParam("nonce") String nonce,
                           @RequestParam("timestamp") String timestamp,
                           @RequestHeader("x-jdy-signature") String signature,
                           @RequestBody String payload) {
        if (!validateSignature(nonce, payload, timestamp, signature)) {
            return "fail";
        }
        // 在这里处理消息
        handleData(payload);

        return "success";
    }

    private void handleData(String payload) {
        // 在这里处理推送来的数据
        JSONObject payloadJSON = JSONUtil.parseObj(payload);
        String op = payloadJSON.getStr("op");
        String data = payloadJSON.getStr("data");

        if (DATA_UPDATE.equals(op)) {
            dates(data);
            create(data);
            update(data);


        }
    }

    // 修改付款单时间信息
    private void dates(String data) {
        Lin lin = JSONUtil.toBean(data, Lin.class);
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameterDelete = new HashMap<>();
        parameterDelete.put("instance_id", lin.get_id());
        parameterDelete.put("tasks_type", 1);
        String jsonSale = JSONUtil.toJsonStr(parameterDelete);
        JSONObject jdySale = ApiClient.sendPostRequest("https://api.jiandaoyun.com/api/v5/workflow/instance/get", headers, jsonSale);
        JdyPurchaseOrder jdyPurchaseOrder = JSONUtil.toBean(jdySale, JdyPurchaseOrder.class);
        if (jdyPurchaseOrder.getStatus() == 1) {
            int size = jdyPurchaseOrder.getTasks().size() - 1;
            boolean d=true;
            boolean c=true;
            for (int i = size; i > 0; i--) {
                if (  jdyPurchaseOrder.getTasks().get(i).getFlow_name().equals("财务审核") &&
                        jdyPurchaseOrder.getTasks().get(i).getFinish_action().equals("forward")&& d){
                    lin.set_widget_1736231012617(jdyPurchaseOrder.getTasks().get(i).getFinish_time());
                    d=false;
                }
                if (jdyPurchaseOrder.getTasks().get(i).getFlow_name().equals("供应链总监审核") &&
                        jdyPurchaseOrder.getTasks().get(i).getFinish_action().equals("forward") && c){
                    lin.set_widget_1736231012618(jdyPurchaseOrder.getTasks().get(i).getFinish_time());
                    c=false;
                }
            }
        }
        Map<String, Object> parameterInster = new HashMap<>();
        parameterInster.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
        // 付款单页面：669cb70dab60aa3f4a7bb8b2
        parameterInster.put("entry_id", "669cb70dab60aa3f4a7bb8b2");
        parameterInster.put("is_start_trigger", "true");
        parameterInster.put("data_id", lin.get_id());
        lin.set_id(null);
        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(lin));
        String jsonSalee = JSONUtil.toJsonStr(parameterInster);
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
    }

    // 修改入库凭证【已付总金额、未付金额、尾款未付总金额】
    private void update(String data) {
        //log.info("付款单的接口类update: {}",  data);
        PaymentForm paymentForm = JSONUtil.toBean(data, PaymentForm.class);
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameterDelete = new HashMap<>();
        parameterDelete.put("instance_id", paymentForm.get_id());
        parameterDelete.put("tasks_type", 1);
        String jsonSale = JSONUtil.toJsonStr(parameterDelete);
        JSONObject jdySale = ApiClient.sendPostRequest("https://api.jiandaoyun.com/api/v5/workflow/instance/get", headers, jsonSale);
        JdyPurchaseOrder jdyPurchaseOrder = JSONUtil.toBean(jdySale, JdyPurchaseOrder.class);
        //log.info("付款单的接口类jdyPurchaseOrder.getStatus(): {}",  jdyPurchaseOrder.getStatus());
        if (jdyPurchaseOrder.getStatus() == 1) {
            // OrderFinalPayment：订单尾款列表
            for (PaymentForm.OrderFinalPayment orderFinalPayment : paymentForm.get_widget_1721548605263()) {
                log.info("付款单的接口类jdyPurchaseOrder.getStatus()1111: {},,{},,{}",  orderFinalPayment.get_widget_1727334556949(), orderFinalPayment.get_widget_1721548605264(), orderFinalPayment.get_widget_1721548605265());
                if (orderFinalPayment.get_widget_1727334556949() == null || orderFinalPayment.get_widget_1727334556949().isEmpty() ||
                        orderFinalPayment.get_widget_1721548605264() == null || orderFinalPayment.get_widget_1721548605264().isEmpty()
                        || orderFinalPayment.get_widget_1721548605265()==null ) {
                    continue; // 跳过当前遍历
                }

                Map<String, Object> parameterCxv = new HashMap<>();
                parameterCxv.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
                // 入库凭证：66a3727ee9d0a8542c969091
                parameterCxv.put("entry_id", "66a3727ee9d0a8542c969091");
                HashMap<String, String> communti = new HashMap<>();
                communti.put("_widget_1727315685608", orderFinalPayment.get_widget_1727334556949());
                communti.put("_widget_1721987711273", orderFinalPayment.get_widget_1721548605264());
                // 只会有一条入库凭证单数据
                List<InvoiceDocument> invoiceDocuments = PurchaseCommunity.queryBased(parameterCxv, headers, communti, InvoiceDocument.class);
                //log.info("付款单的接口类invoiceDocuments: {}",  invoiceDocuments);
                if (invoiceDocuments == null || invoiceDocuments.isEmpty()) {
                    continue; // 跳过当前遍历
                }

                // 获取尾款占比
                BigDecimal finalPaymentRate = BigDecimal.valueOf(orderFinalPayment.get_widget_1721548605265());

                // 定义变量用于存储分摊金额总和和未付金额总和
                BigDecimal totalAllocationAmount = BigDecimal.ZERO;
                BigDecimal totalUnpaidAmount = BigDecimal.ZERO;
                BigDecimal totalBalanceAmount = BigDecimal.ZERO;
                InvoiceDocument document = invoiceDocuments.getFirst();
                //log.info("付款单的接口类document: {}",  document);
                for (InvoiceDocument.InvoiceLineItem invoiceLineItem : document.get_widget_1727340673732()) {
                    //把其他采购订单的付款金额拿过来。
                    Map<String, Object> cgdd = new HashMap<>();
                    cgdd.put("app_id", "6690c7633df0f4b90b4ef551");
                    //采购订单_拷贝数据（陈志生）669df675b02f2a74e35ca2f9
                    cgdd.put("entry_id", "669df675b02f2a74e35ca2f9");

                    communti.put("_widget_1721628277543", invoiceLineItem.get_widget_1727340673739());
                    communti.put("_widget_1721628277558", invoiceLineItem.get_widget_1727340673735());
                    List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(cgdd, headers, communti, SAPPurchaseOrder.class);
                    // 含税金额不能为空
                    if (sapPurchaseOrders.isEmpty() || sapPurchaseOrders.getFirst() == null ||
                            sapPurchaseOrders.getFirst().get_widget_1724225500094() == null) {
                        continue;
                    }

                    // 如果采购订单查询结果不为空，取出已付金额
                    /*BigDecimal paidAmount = sapPurchaseOrders.isEmpty() || sapPurchaseOrders.getFirst() == null ||
                            sapPurchaseOrders.getFirst().get_widget_1722475785243() == null
                            ? BigDecimal.ZERO
                            : BigDecimal.valueOf(sapPurchaseOrders.getFirst().get_widget_1722475785243());*/


                    // 计算尾款分摊金额
                    BigDecimal allocationAmount = invoiceLineItem.get_widget_1727340673745()
                            .multiply(finalPaymentRate)
                            .setScale(10, RoundingMode.HALF_UP);

                    // 如果原分摊字段有数据，累加现有值；否则直接写入
                    BigDecimal existingAllocationAmount = invoiceLineItem.get_widget_1731575068806();
                    if (existingAllocationAmount != null) {
                        allocationAmount = allocationAmount.add(existingAllocationAmount);
                    }
                    invoiceLineItem.set_widget_1731575068806(allocationAmount);

                    // 计算未付金额 unpaidAmount
                    BigDecimal zongshu = invoiceLineItem.get_widget_1727340673745();
                            //隐藏.add(sapPurchaseOrders.getFirst().get_widget_1724225500094());

                    BigDecimal unpaidAmount = zongshu
                            .subtract(allocationAmount)
                            //.subtract(paidAmount)
                            .setScale(10, RoundingMode.HALF_UP);

                    // 明细表未付金额
                    invoiceLineItem.set_widget_1731575068807(unpaidAmount);


                    // 计算分摊总金额累加值：已付金额减去未付金额，加上当前行的分摊金额
                    BigDecimal allocationAdjustment = allocationAmount;//paidAmount.add(allocationAmount);

                    // 累加到分摊金额总和和未付金额总和
                    totalAllocationAmount = totalAllocationAmount.add(allocationAdjustment);
                    totalUnpaidAmount = totalUnpaidAmount.add(unpaidAmount);
                    totalBalanceAmount = totalBalanceAmount.add(invoiceLineItem.get_widget_1727340673745().subtract(allocationAmount));

                    // 处理尾款的采购订单_拷贝数据表逻辑 669df675b02f2a74e35ca2f9
                    sapPurchaseOrders.getFirst().set_widget_1722475785243(allocationAdjustment.setScale(2, RoundingMode.HALF_UP).doubleValue());
                    sapPurchaseOrders.getFirst().set_widget_1731911494439(unpaidAmount);
                    sapPurchaseOrders.getFirst().set_widget_1722475785245(allocationAmount.setScale(2, RoundingMode.HALF_UP).doubleValue());

                    Map<String, Object> parameterEnd = new HashMap<>();
                    parameterEnd.put("app_id", "6690c7633df0f4b90b4ef551");
                    //采购订单_拷贝数据（陈志生）669df675b02f2a74e35ca2f9
                    parameterEnd.put("entry_id", "669df675b02f2a74e35ca2f9");
                    parameterEnd.put("is_start_trigger", "true");
                    parameterEnd.put("data_id", sapPurchaseOrders.getFirst().get_id());
                    sapPurchaseOrders.getFirst().set_id(null);
                    parameterEnd.put("data", ConnmeUtils.convertEntityToMapNull(sapPurchaseOrders.getFirst()));
                    String jsonSaleEnd = JSONUtil.toJsonStr(parameterEnd);
                    //log.info("M付款单的接口类updateParam: {}", jsonSaleEnd);
                    ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSaleEnd);

                }

                // 输出分摊金额总和和未付金额总和到总记录
                BigDecimal existingTotalAllocationAmount = invoiceDocuments.getFirst().get_widget_1731638214169();
                BigDecimal existingTotalUnpaidAmount = invoiceDocuments.getFirst().get_widget_1731638214170();

                if (existingTotalAllocationAmount != null) {
                    totalAllocationAmount = totalAllocationAmount.add(existingTotalAllocationAmount);
                }
                if (existingTotalUnpaidAmount != null) {
                    totalUnpaidAmount = totalUnpaidAmount.add(existingTotalUnpaidAmount);
                }

                invoiceDocuments.getFirst().set_widget_1731638214169(totalAllocationAmount);
                invoiceDocuments.getFirst().set_widget_1731638214170(totalUnpaidAmount);
                invoiceDocuments.getFirst().set_widget_1731915520417(totalBalanceAmount);


                Map<String, Object> parameterInster = new HashMap<>();
                parameterInster.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
                // 入库凭证：66a3727ee9d0a8542c969091
                parameterInster.put("entry_id", "66a3727ee9d0a8542c969091");
                parameterInster.put("is_start_trigger", "true");
                parameterInster.put("data_id", invoiceDocuments.getFirst().get_id());
                invoiceDocuments.getFirst().set_id(null);
                parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(invoiceDocuments.getFirst()));
                String jsonSalee = JSONUtil.toJsonStr(parameterInster);
                //log.info("付款单的接口类更改数据: {}", jsonSalee);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
            }
        }
    }


    // 处理预付款
    private void create(String data) {
        //log.info("付款单的接口类create: {}", data);
        Header[] headers = ConnmeUtils.createHeaders();
        Fukuandan fukuandan = JSONUtil.toBean(data, Fukuandan.class);
        if (fukuandan.getFlowState() != 1 || fukuandan.get_widget_1721546510495()==null) {
            return;
        }
        Map<String, Map<String, Double>> yushou = new HashMap<>();

        for (Fukuandan.Yufu yufu : fukuandan.get_widget_1721546510495()) {
            if (yushou.containsKey(yufu.get_widget_1721546510504())) {
                Map<String, Double> stringDoubleMap = yushou.get(yufu.get_widget_1721546510504());
                if (stringDoubleMap.containsKey(yufu.get_widget_1721616942683())) {
                    Double aDouble = yushou.get(yufu.get_widget_1721546510504()).get(yufu.get_widget_1721616942683());
                    stringDoubleMap.put(yufu.get_widget_1721616942683(), yufu.get_widget_1721546510520() + aDouble);
                } else {
                    stringDoubleMap.put(yufu.get_widget_1721616942683(), yufu.get_widget_1721546510520());
                }

            } else {
                Map<String, Double> yushou001 = new HashMap<>();
                yushou001.put(yufu.get_widget_1721616942683(), yufu.get_widget_1721546510520());
                yushou.put(yufu.get_widget_1721546510504(), yushou001);
            }
        }
        chuliYuSuan(headers, yushou);
    }

    // 对采购订单_拷贝数据（陈志生）表的数据更改 【已付金额、未付金额】
    private void chuliYuSuan(Header[] headers, Map<String, Map<String, Double>> weikuan) {
        weikuan.forEach((key, innerMap) -> {
            try {
                Map<String, Object> parameterCxv = new HashMap<>();
                parameterCxv.put("app_id", "6690c7633df0f4b90b4ef551");
                parameterCxv.put("entry_id", "669df675b02f2a74e35ca2f9");
                //采购订单_拷贝数据（陈志生）669df675b02f2a74e35ca2f9
                //log.info("Processing innerMap: " + innerMap);
                innerMap.forEach((innerKey, value) -> {
                    HashMap<String, String> communti = new HashMap<>();

                    communti.put("_widget_1721628277543", key);
                    communti.put("_widget_1721628277558", innerKey);
                    List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(parameterCxv, headers, communti, SAPPurchaseOrder.class);
                    //log.info("Processing inner key: " + innerKey + ", value: " + value);
                    SAPPurchaseOrder salesOrderKu = sapPurchaseOrders.get(0);
                    if (salesOrderKu == null) {
                        log.error("SalesOrderKu is null for key: " + key);
                        return;
                    }

                    /*if (sapPurchaseOrders.getFirst().get_widget_1722475785243() != null) {
                        sapPurchaseOrders.getFirst().set_widget_1722475785243(sapPurchaseOrders.getFirst().get_widget_1722475785243() + value);
                    } else {
                        sapPurchaseOrders.getFirst().set_widget_1722475785243(value);
                    }*/
                    sapPurchaseOrders.getFirst().set_widget_1722475785243(value);
                    BigDecimal subtract = sapPurchaseOrders.getFirst().get_widget_1724225500094().subtract(BigDecimal.valueOf(sapPurchaseOrders.getFirst().get_widget_1722475785243()));
                    sapPurchaseOrders.getFirst().set_widget_1731911494439(subtract);

                    Map<String, Object> parameterInster = new HashMap<>();
                    parameterInster.put("app_id", "6690c7633df0f4b90b4ef551");
                    //采购订单_拷贝数据（陈志生）669df675b02f2a74e35ca2f9
                    parameterInster.put("entry_id", "669df675b02f2a74e35ca2f9");
                    parameterInster.put("is_start_trigger", "true");
                    parameterInster.put("data_id", sapPurchaseOrders.getFirst().get_id());
                    sapPurchaseOrders.getFirst().set_id(null);
                    parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(sapPurchaseOrders.getFirst()));
                    String jsonSale = JSONUtil.toJsonStr(parameterInster);
                    //log.info("付款单的接口类更改数据chuliYuSuan: " + jsonSale);
                    ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);

                });

            } catch (Exception e) {
                log.error("Error processing key: {}", key, e);
            }
        });


    }

    private boolean validateSignature(String nonce, String payload, String timestamp, String signature) {
        String calculatedSignature = getSignature(nonce, payload, FuKuanDanController.SECRET, timestamp);
        return calculatedSignature.equals(signature);
    }

    private String getSignature(String nonce, String payload, String secret, String timestamp) {
        return DigestUtils.sha1Hex(nonce + ":" + payload + ":" + secret + ":" + timestamp);
    }

    @PostMapping("/countSalesOrderToChanges")
    public String countSalesOrderToChanges(@RequestParam("nonce") String nonce,
                           @RequestParam("timestamp") String timestamp,
                           @RequestHeader("x-jdy-signature") String signature,
                           @RequestBody String payload) {
        if (!validateSignature(nonce, payload, timestamp, signature)) {
            return "fail";
        }
        // 在这里处理消息
        handleDataToChanges(payload);

        return "success";
    }

    private void handleDataToChanges(String payload) {
        // 在这里处理推送来的数据
        JSONObject payloadJSON = JSONUtil.parseObj(payload);
        String op = payloadJSON.getStr("op");
        String data = payloadJSON.getStr("data");

        if (DATA_CREATE.equals(op)) {
            updateToChanges(data);
        }
    }

    private void updateToChanges(String datas) {
        ChenToChangesVO chenToChangesVO = JSONUtil.toBean(datas, ChenToChangesVO.class);

        List<SalesOrder> salesOrderList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "667230ad22a8581756b77d52");
        parameter.put("entry_id", "667230b322a8581756b78353");

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");

        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "ne");
        List<Integer> values = new ArrayList<>();
        values.add(2);
        cond.put("value", values);

        Map<String, Object> orderNoCond = new HashMap<>();
        orderNoCond.put("field", "_widget_1718759603973"); // 销售订单号字段
        orderNoCond.put("type", "text"); // 订单号为文本类型
        orderNoCond.put("method", "eq"); // 等于
        List<String> orderNoValues = new ArrayList<>();
        orderNoValues.add(chenToChangesVO.get_widget_1751600206672());
        orderNoCond.put("value", orderNoValues);

        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        conds.add(orderNoCond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<SalesOrder> list = JSONUtil.toList(objects, SalesOrder.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            salesOrderList.addAll(list);
        } while (fale);
        // 新增处理逻辑：分组、排序、计算并构建ToChangeVO
        List<ToChangeVO> toChangeVOList = new ArrayList<>();

        // 1. 按销售订单号分组（_widget_1718759603973）
        Map<String, List<SalesOrder>> orderGroupMap = salesOrderList.stream()
                .filter(order -> order.get_widget_1718759603973() != null) // 过滤订单号为空的记录
                .collect(Collectors.groupingBy(SalesOrder::get_widget_1718759603973));

        // 2. 处理每个分组
        for (Map.Entry<String, List<SalesOrder>> entry : orderGroupMap.entrySet()) {
            String orderNo = entry.getKey(); // 销售订单号
            List<SalesOrder> orderList = entry.getValue();

            // 2.1 按提交时间（createTime）升序排序（最早的在前）
            orderList.sort(Comparator.comparing(SalesOrder::getCreateTime));

            // 2.2 提取第一次提交时间（作为累计天数的基准）
            if (orderList.isEmpty()) {
                continue;
            }
            SalesOrder firstOrder = orderList.getFirst();
            DateTime firstCreateTime = firstOrder.getCreateTime();
            if (firstCreateTime == null) {
                log.warn("销售订单[{}]的第一条记录提交时间为空，跳过处理", orderNo);
                continue;
            }

            // 2.3 遍历分组内的每条记录，构建ToChangeVO
            for (int i = 0; i < orderList.size(); i++) {
                SalesOrder currentOrder = orderList.get(i);
                ToChangeVO vo = new ToChangeVO();
                vo.set_id(currentOrder.get_id()); // 使用原记录的ID

                // 构建信息字符串
                String info = buildChangeInfo(i, currentOrder, firstCreateTime);
                vo.set_widget_1751512353683(info);

                toChangeVOList.add(vo);
            }
        }

        // 3. 此处可添加将toChangeVOList插入简道云表单的逻辑
        for (ToChangeVO vo : toChangeVOList) {
            Map<String, Object> parameterInster = new HashMap<>();
            parameterInster.put("app_id", "667230ad22a8581756b77d52");
            parameterInster.put("entry_id", "667230b322a8581756b78353");
            parameterInster.put("is_start_trigger", "true");
            parameterInster.put("data_id", vo.get_id());
            vo.set_id(null);
            parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(vo));
            String jsonSalee = JSONUtil.toJsonStr(parameterInster);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
        }
    }

    /**
     * 构建每条修改记录的信息字符串
     * @param index 记录索引（0表示第一次提交，1表示第二次提交，以此类推）
     * @param currentOrder 当前记录
     * @param firstCreateTime 第一次提交时间（基准时间）
     * @return 格式化的信息字符串
     */
    private String buildChangeInfo(int index, SalesOrder currentOrder, DateTime firstCreateTime) {
        // 日期格式化器（转换为"yyyy年MM月dd日"）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");

        // 转换第一次提交时间为LocalDate
        LocalDateTime firstCreateLdt = convertToLocalDateTime(firstCreateTime);
        if (firstCreateLdt == null) {
            return "时间格式错误：第一次提交时间无效";
        }

        // 处理当前记录的时间
        DateTime currentCreateTime = currentOrder.getCreateTime();
        LocalDateTime currentCreateLdt = convertToLocalDateTime(currentCreateTime);
        String currentCreateStr = currentCreateLdt != null ?
                currentCreateLdt.format(formatter) : "提交时间未知";

        DateTime currentReviewTime = currentOrder.getReview_date();
        LocalDateTime currentReviewLdt = convertToLocalDateTime(currentReviewTime);
        String currentReviewStr = currentReviewLdt != null ?
                currentReviewLdt.format(formatter) : "未审批";

        // 计算累计审批天数（第一次提交到当前审批的天数差）
        String daysDiffStr = "未知";
        if (currentReviewLdt != null) {
            long days = ChronoUnit.DAYS.between(firstCreateLdt.toLocalDate(), currentReviewLdt.toLocalDate());
            daysDiffStr = days + "天";
        }

        // 根据索引构建不同的信息
        if (index == 0) {
            // 第一次提交
            return String.format(
                    "第一次提交日期：%s；第一次审批通过时间：%s；累计审批天数：%s",
                    currentCreateStr, currentReviewStr, daysDiffStr
            );
        } else {
            // 第n次修改（n = index）
            String changeContent = currentOrder.get_widget_1727337368903() != null ?
                    currentOrder.get_widget_1727337368903() : "无修改内容";

            return String.format(
                    "第%d次修改内容：%s；第%d次提交日期：%s；第%d次审批通过时间：%s；累计审批天数：%s",
                    index, changeContent, index + 1, currentCreateStr, index + 1, currentReviewStr, daysDiffStr
            );
        }
    }

    /**
     * 将DateTime转换为LocalDateTime（处理空值和时区）
     */
    /**
     * 将 Joda-Time 的 DateTime 转换为 Java 8 的 LocalDateTime
     */
    private LocalDateTime convertToLocalDateTime(DateTime dateTime) {
        if (dateTime == null) {
            return null;
        }
        // 先格式化为字符串（确保格式与你的数据一致）
        String dateStr = dateTime.toString("yyyy-MM-dd HH:mm:ss");
        // 使用 Java 8 的 DateTimeFormatter 解析
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.parse(dateStr, formatter);
    }
}
